<template>
  <!-- 仅 UI：输入框 + 上/下/关闭按钮；固定右上角浮层 -->
  <v-text-field
    v-if="showFind"
    ref="findInputRef"
    v-model="findText"
    :autofocus="true"
    bg-color="rgb(var(--v-theme-surface))"
    class="mr-2 find-input find-panel"
    flat
    hide-details
    :placeholder="t('find.placeholder')"
    rounded="xl"
    variant="outlined"
    @keydown.enter.prevent="nextPrev(1)"
    @keydown.esc.stop.prevent="onClose"
  >
    <template #append-inner>
      <span v-if="findData" class="text-caption font-weight-light"
        >{{ findData.activeMatchOrdinal }}/{{ findData.matches }}</span
      >
      <v-btn :icon="mdiChevronUp" size="x-small" variant="text" @click="nextPrev(-1)" />
      <v-btn :icon="mdiChevronDown" size="x-small" variant="text" @click="nextPrev(1)" />
      <v-btn :icon="mdiClose" size="x-small" variant="text" @click="onClose" />
    </template>
  </v-text-field>
</template>

<script lang="ts" setup>
import { nextTick, onUnmounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { EscPriority, register } from '@/utils/esc-manager'
import { shortcutEvents } from '@/utils/shortcut-events'
import { mdiChevronDown, mdiChevronUp, mdiClose } from '@mdi/js'

const { t } = useI18n()

const props = defineProps<{
  tab: F2.tab.Entity
}>()

const showFind = ref(false)
const findText = ref('')
const findData = ref<Electron.Result | null>(null)

const options = ref<Electron.FindInPageOptions>({
  forward: true,
  findNext: false
})
const webContentsId = computed(() => props.tab.webContentsId)

const findInputRef = ref<any>(null)

function focusFindInput() {
  nextTick(() => {
    const fallback = document.querySelector<HTMLInputElement>('.find-panel .find-input input')
    if (fallback) {
      fallback.focus()
      fallback.select()
    }
  })
}

_pre_.tab.onFindInPage((data, websId) => {
  if (websId !== webContentsId.value) return
  findData.value = data
})

// 订阅主进程快捷键事件：切换查找浮层（仅在匹配的 webContents 上响应）
shortcutEvents.onFindToggle(sourceId => {
  if (sourceId && sourceId !== webContentsId.value) return
  if (showFind.value) {
    focusFindInput()
  } else {
    showFind.value = true
  }
  _pre_.tab.focus()
})

function nextPrev(v: -1 | 1) {
  if (!findData.value) return
  options.value.findNext = false

  options.value.forward = v > 0
  inputFindText()
}

function onClose() {
  findText.value = ''
  findData.value = null
  _pre_.tab.stopFindInPage(webContentsId.value)
  showFind.value = false
}

watch(
  () => webContentsId.value,
  () => {
    onClose()
  }
)

function inputFindText(e?: string) {
  if (e) {
    options.value = {
      forward: true,
      findNext: true
    }
  }
  if (findText.value) {
    _pre_.tab.findInPage(toRaw(findText.value), toRaw(options.value), webContentsId.value)
  } else {
    findData.value = null
    _pre_.tab.stopFindInPage(webContentsId.value)
  }
}

let unregisterEsc: undefined | (() => void)
watch(showFind, v => {
  if (v) {
    unregisterEsc = register({
      id: `find-${webContentsId.value}`,
      priority: EscPriority.FIND,
      onEsc: () => {
        if (showFind.value) {
          onClose()
          return true
        }
      }
    })
  } else {
    unregisterEsc?.()
    unregisterEsc = undefined
  }
})

onUnmounted(() => unregisterEsc?.())

watch(findText, val => {
  inputFindText(val)
})
</script>

<style scoped>
.find-panel {
  z-index: 9999;
  position: absolute;
  width: 200px;
}
.find-input :deep(.v-field__input) {
  font-weight: 400;
  font-size: 13px;
  min-height: 26px !important;
  padding-top: 1px !important;
  padding-bottom: 0 !important;
}
</style>

<i18n>
{
  "zhHans": {
    "find": {
      "placeholder": "查找页面"
    }
  },
  "en": {
    "find": {
      "placeholder": "Find in page"
    }
  }
}
</i18n>
